import axios from 'axios'
import {
  Message,
  MessageBox
} from 'element-ui'
import store from '../store'
import {
  getToken,
  removeToken
} from '@/utils/auth'
import router from "@/router";
// const data=window.location.href.substring(window.location.href.lastIndexOf('.')+1).substr(0, window.location.href.substring(window.location.href.lastIndexOf('.')+1).length - 1);
// 创建axios实例
let service = axios.create({
  // baseURL:`https://omsapi.dushisc.${data}:8081`, // api的base_url
  baseURL: "",
  timeout: 5000 // 请求超时时间
})
axios.defaults.withCredentials = true;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
// request拦截器
service.interceptors.request.use(config => {
  // 请求的数据格式为 json
  // if (store.getters.token) {
  //   config.headers = {
  //     'Authorization': "Token " + getToken('Token'), //携带权限参数
  //   };
  config.headers.token = getToken('Token')
  return config
}, error => {
  Promise.reject(error, 444444444444444444)
})

// respone拦截器
const token = getToken('Token')
service.interceptors.response.use(
  response => {
    /**
     * code:200,接口正常返回;
     */
    const res = response
    if (res.status !== 200) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
      // 根据服务端约定的状态码：5001:非法的token; 5002:其他客户端登录了; 5004:Token 过期了;
      if (res.status === 5001 || res.status === 5002 || res.status === 5004) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      return Promise.reject('error')
    } else {
      // 当code码返回为10000的时候是正确的其余是错误
      if (res.data.code == 10000 || res.data.code == 21251 || res.data.code == 10103 ) {
        return response.data
      } else if (res.data.code == 10104) {
        removeToken("Token")
        this.$router.push({ path: '/permission/login' })
      } else {
        if (res.data.message) {
          Message({
            message: res.data.message,
            type: 'warning',
          })
        }
        return response.data
      }
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    if (error.response.status === 401) {
      removeToken("Token")
      router.push({ path: '/login' })
    }
    return Promise.reject(error)
  }
)

export default service